clc;
clear all;
close all;
character=['M','U','Y','X'];
priority=[0.4,0.2,0.1,0.3];
char_a=0;
string=input('Enter a string you want to encode:');
display(string);
len=length(string);
if(length(character)==length(priority) && sum(priority)==1)  
 
% Calculate the Symbol Intervals.
rx=zeros(1,length(character));
for i=1:length(character)
if i==1
rx(i)=priority(i);
else
rx(i)=rx(i-1)+priority(i);
end
end

 
    L=0;U=1; % Initial Lower and Upper Intervals.
 
for i=1:length(string)
        j=find(string(i)==character);   % Finds the Index of the sequence symbol in the symbol string.
if(j==1)
L_new=L;
display(L_new);
else
L_new=L+(U-L)*rx(j-1);
display(L_new);
end
U_new=L+(U-L)*rx(j);
display(U_new);
        L=L_new;
        U=U_new;
range=U-L;
        len1=length(string)-1;
if (i<len1+1)
    l=1;
L_alph=L+range*0;
arr(l)=L_alph;
l=l+1;
for j=1:length(character);
H_alph=L+range*rx(j);
arr(l)=H_alph;
l=l+1;
%display(H_alph);
end
display(arr);
end
end
else
display('Please enter proper values!!');
end
%display tag value
tag=(L+U)/2;
display('TAG VALUE IS:');
disp(tag);
m=1;
 
 
% Decoding the Sequence of Symbols.
if(length(character)==length(priority) && sum(priority)==1)
rx=zeros(1,length(character));
for i=1:length(character)
if i==1
rx(i)=priority(i);
else
rx(i)=rx(i-1)+priority(i);
end
end
display(rx);                    %display range
 
%calculate tag values till length of string pass by user
 
for i=1:length(string)
char_a(m)=tag;
       m=m+1;
display(tag);
       L1=0;
       j=1;
for j=1:length(rx)
if(rx(j)>tag)
             k=j;
break
end
end
if k==1
           L_new1=L1;
else
           L_new1=rx(k-1);
end
       U_new1=rx(k);
range=U_new1-L_new1;
tag_new=(tag-L_new1)/range;
tag=tag_new;
end
end
 
display(char_a);
 
%display characters
 
for i=1:length(char_a);
for j=1:length(rx)
if(rx(j)>char_a(i))
priority=j;
break
end
end
display(character(priority));
end
